<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { Role } from '#/api/system/role';

import { useRouter } from 'vue-router';

import { useAccess } from '@vben/access';
import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { getVxePopupContainer } from '@vben/utils';

import {
  Dropdown,
  Menu,
  MenuItem,
  Modal,
  Popconfirm,
  Space,
} from 'ant-design-vue';

import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import { roleChangeStatus, roleList, roleRemove } from '#/api/system/role';
import { TableSwitch } from '#/components/table';

import { columns, querySchema } from './data';
import roleAuthModal from './role-auth-modal.vue';
import roleDrawer from './role-drawer.vue';

const formOptions: VbenFormProps = {
  schema: querySchema(),
  fieldMappingTime: [
    [
      'createTime',
      ['params[beginTime]', 'params[endTime]'],
      ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
    ],
  ],
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    checkMethod: ({ row }) => row.id !== '1',
  },
  columns: columns(),
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        return await roleList({
          current: page.currentPage,
          size: page.pageSize,
          ...formValues,
        });
      },
    },
  },
  id: 'system-role-index',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});
const [RoleDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: roleDrawer,
});

function handleAdd() {
  drawerApi.setData({});
  drawerApi.open();
}

async function handleEdit(record: Role) {
  drawerApi.setData({ id: record.id });
  drawerApi.open();
}

async function handleDelete(row: Role) {
  await roleRemove([row.id]);
  await tableApi.query();
}

function handleMultiDelete() {
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: Role) => row.id);
  Modal.confirm({
    title: $t('common.tip'),
    okType: 'danger',
    content: $t('ui.actionMessage.deleteConfirm', [ids.length]),
    onOk: async () => {
      await roleRemove(ids);
      await tableApi.query();
    },
  });
}

const { hasAccessByCodes } = useAccess();

const [RoleAuthModal, authModalApi] = useVbenModal({
  connectedComponent: roleAuthModal,
});

function handleAuthEdit(record: Role) {
  authModalApi.setData({ id: record.id });
  authModalApi.open();
}

const router = useRouter();
function handleAssignRole(record: Role) {
  router.push(`/system/role-assign/${record.id}`);
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable :table-title="$t('system.role.tableTitle')">
      <template #toolbar-tools>
        <Space>
          <a-button
            :disabled="!vxeCheckboxChecked(tableApi)"
            danger
            type="primary"
            @click="handleMultiDelete"
          >
            {{ $t('common.delete') }}
          </a-button>
          <a-button type="primary" @click="handleAdd">
            {{ $t('common.create') }}
          </a-button>
        </Space>
      </template>
      <template #status="{ row }">
        <TableSwitch
          v-model="row.status"
          :api="() => roleChangeStatus(row)"
          :disabled="row.id === 1 || !hasAccessByCodes(['system:role:edit'])"
          :reload="() => tableApi.query()"
        />
      </template>
      <template #action="{ row }">
        <!-- 租户管理员不可修改admin角色 防止误操作 -->
        <!-- 超级管理员可通过租户切换来操作租户管理员角色 -->
        <Space>
          <ghost-button @click.stop="handleEdit(row)">
            {{ $t('common.edit') }}
          </ghost-button>
          <Popconfirm
            :get-popup-container="getVxePopupContainer"
            placement="left"
            :title="$t('common.deleteConfirm')"
            @confirm="handleDelete(row)"
          >
            <ghost-button danger @click.stop="">
              {{ $t('common.delete') }}
            </ghost-button>
          </Popconfirm>
        </Space>
        <Dropdown
          :get-popup-container="getVxePopupContainer"
          placement="bottomRight"
        >
          <template #overlay>
            <Menu>
              <MenuItem key="1" @click="handleAuthEdit(row)">
                {{ $t('system.role.dataPermission') }}
              </MenuItem>
              <MenuItem key="2" @click="handleAssignRole(row)">
                {{ $t('system.role.assignUser') }}
              </MenuItem>
            </Menu>
          </template>
          <a-button size="small" type="link">
            {{ $t('common.more') }}
          </a-button>
        </Dropdown>
      </template>
    </BasicTable>
    <RoleDrawer @reload="tableApi.query()" />
    <RoleAuthModal @reload="tableApi.query()" />
  </Page>
</template>
